<?php

namespace app\install\controller;

use think\Controller;
use think\Request;
use think\Db;
use think\facade\Config;
use think\facade\Env;
class Index extends Controller
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {   
       
        session('step',0);
        session('error',false);
        return view();
    }

    
    public function step1()
    {   
        if(session('step')!=0 && session('step')!=2){
            $this->redirect('index');
        }
        session('error',false);
        $envArr=check_env();
        $funs=check_funs();
        $dirs=check_dir();
        $this->assign([
            'envArr'=>$envArr,
            'funs'  =>$funs,
            'dirs'=>$dirs,
        ]);
        session('step',1);
        return view();
    }

  
    public function step2()
    {
        if(request()->isPost()){
            $data=input('post.');
            $dbArr=$data['db'];
            $adminArr=$data['admin'];
            // 检查用户信息是否完整
            if(!is_array($adminArr) || empty($adminArr['admin'])||empty($adminArr['password'])||empty($adminArr['rpassword'])||empty($adminArr['site_name'])){
                $this->error('管理员信息不完整，请检查！');
            }else{
                if(!preg_match('/^[a-zA-Z0-9_-]{5,10}$/',$adminArr['admin'])){
                    $this->error('账号格式错误');
                }
                if(!preg_match('/^[a-zA-Z0-9_-]{5,10}$/',$adminArr['password'])){
                    $this->error('密码格式错误');
                }else{
                    if($adminArr['password']!=$adminArr['rpassword']){
                        $this->error('两次密码输入不一致');
                    }else{
                        $adminArr=serialize($adminArr);
                        session('admin_info',$adminArr);
                    }
                }
            }
            // 检查数据库
            if(!is_array($dbArr) || empty($dbArr['hostname']) || empty($dbArr['database']) || empty($dbArr['username']) || empty($dbArr['password']) || empty($dbArr['prefix']) || empty($dbArr['hostport'])){
                $this->error('数据库信息不完整');
            }else{
                $db_Arr=serialize($dbArr);//序列化后存入session
                session('db_config',$db_Arr);
                $dbname=$dbArr['database'];
                unset($dbArr['database']);//删除数据库
                $db=Db::connect($dbArr);//动态配置数据库连接信息
                $sql="CREATE DATABASE IF NOT EXISTS {$dbname} DEFAULT CHARACTER SET utf8";
               
                if(!$db->execute($sql)){//执行sql语句
                    $this->error($db->getError());
                }else{
                    $this->success('创建成功！',url('step3',['access'=>'success']));
                }
            }
            return;
        }
        if(session('error')){
            $this->error('环境检查不通过，请配置系统要求环境后再试');
        }
        $step=session('step');
        if($step!=1 && $step!=2){
            $this->redirect('step1');
        }
        session('step',2);
        return view();
    }

   
    public function step3()
    {
        if(input('access')!='success' && session('step')!=2){
            $this->redirect('index');
        }
        session('step',3);
        echo $this->fetch();
        $db_config=session('db_config');
        $db_config=unserialize($db_config);
        $db=Db::connect($db_config);
        // 创建数据表
        create_tables($db,$db_config['prefix']);
        // 初始化
        // 添加管理
        $admin=unserialize(session('admin_info'));
        //替换数据库相关配置
        $databaseConfig['hostname'] = $db_config['hostname'];
        $databaseConfig['database'] = $db_config['database'];
        $databaseConfig['username'] = $db_config['username'];
        $databaseConfig['password'] = $db_config['password'];
        $databaseConfig['hostport'] = $db_config['hostport'];
        $databaseConfig['prefix'] = $db_config['prefix'];
        $putConfig = @file_put_contents( Env::get('root_path').'config/database.php', "<?php\nreturn \n" . var_export($databaseConfig, true) . "\n;");
        if (!$putConfig) {
            $this->error('安装失败、请确定database.php是否有写入权限');
            
        }
        $result = @file_put_contents($lockFile, 1);
        if (!$putConfig) {
            $this->error('安装失败、请确定install.lock是否有写入权限');
        }
        $this->success('系统安装成功','index/index/index');
        }
       
      
    }

    
}
